
$(document).ready(function () {
	$('#groupfields ul').hide();
	$('#groupfields ul:first').show();
	$('#grouptab span:first').addClass('current');
	$('#grouptab span a').click(function () {
		// Focus current tab
		$('#grouptab span').removeClass('current');
		$(this).parent().addClass('current');

		// Show current group
		var currentTab = $(this).attr('href');
		$('#groupfields ul').hide();
		$(currentTab).show();

		return false;
	});

	// Lead activity
	$('div.form-table').hide();
	$('div.form-table:first').show();
	$('#groupActivity span:first').addClass('current');
	$('#groupActivity span a').click(function () {
		// Focus current tab
		$('#groupActivity span').removeClass('current');
		$(this).parent().addClass('current');

		// Show current group
		var currentTab = $(this).attr('href');
		$('div.form-table').hide();
		$(currentTab).show();

		if (currentTab == "#appointment") {
			resizeAppointment();
		}
		else {
			resizeAction();
		}
		return false;
	});

	// Collspan/ Expand
	$('ul.accordeon-tabs li').each(function () {
		$(this).find(".tab").click(function () {
			if ($(this).parent().attr("class") == "open") {
				$(this).parent().removeClass("open");
				$(this).parent().addClass("close");
				$(this).parent().find(".panel").css("display", "none");
			}
			else {
				$(this).parent().removeClass("close");
				$(this).parent().addClass("open");
				$(this).parent().find(".panel").css("display", "block");
			}
		});
	});

	// Set time
	var nowDate = new Date();

	$(".calendar-date").datepicker();
	$(".calendar-time").timepicker();
	$(".start-time").timepicker({ hour: nowDate.getHours(), minute: nowDate.getMinutes() });
	$(".calendar-datetime").datetimepicker();
	$(".cal").datepicker();

	// Hide model
	$('.fancybox-wrap').hide();
	resizeAction();
});


// Change position for 2 action edit|delete
// auto scale height when display a scroll
$(window).resize(function () {
	resizeAction();
	resizeAppointment();
});

function resizeAppointment() {
	var height = 0;
	$('#app-list LI').each(function () {
		height += $(this).height() + 15;
	});


	// Set position for 2 acts
	if (height > 150) {
		$('#app-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:0px");
				$(this).find('.colact').attr("style", "margin-left:0px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:3px");
				$(this).find('.colact').attr("style", "margin-left:5px");
			}
		});
	}
	else {
		$('#app-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:-5px");
				$(this).find('.colact').attr("style", "margin-left:-10px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:-2px");
				$(this).find('.colact').attr("style", "margin-left:-5px");
			}
		});
	}
}

function resizeAction() {
	var height = 0;
	$('#action-list LI').each(function () {
		height += $(this).height() + 15;
	});

	// Set position for 2 acts
	if (height > 150) {
		$('#action-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:0px");
				$(this).find('.col3').attr("style", "margin-left:0px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:2px");
				$(this).find('.col3').attr("style", "margin-left:5px");
			}
		});
	}
	else {
		$('#action-list LI').each(function () {
			if (!is_ie8) {
				$(this).find('.col2').attr("style", "margin-left:-5px");
				$(this).find('.col3').attr("style", "margin-left:-4px");
			}
			else {
				$(this).find('.col2').attr("style", "margin-left:-2px");
				$(this).find('.col3').attr("style", "margin-left:0px");
			}
		});
	}
}

// Email Opt-Out function
function SentEmailOptOut(id, email) {
	$('#leadId').val(id);
	$('#email').val(email);
	$('#popup').showPopup({
		width: 490
	});
	$('#fancybox-overlay').show();
}


function SendEmail() {
	var id = $('#leadId').val();
	var dataPost = { "id": id, "email": $('#email').val() }

	// Ajax request
	$.ajax({
		type: "POST",
		url: "/Lead/EmailOptOut",
		data: dataPost,
		dataType: "json",
		success: function(model, textStatus, jqXHR) {
			if (typeof model != "undefined" && (model === "" || typeof model.Error == "undefined" || !model.Error)) {
				closePopup();
				window.location.href = '/Lead/Edit/' + id;
			}
			else {
				showPopupError();
			}
		},
		error: function(xhr, status, error) {
			showPopupError();
		}
	});
}

function closePopup() {
	$('#popup').hide();
	$('#fancybox-overlay').hide();
}

//$("form").validate({ submitHandler: editLeadViewModel.Submit });
$(document).ready(function() {
	$("form#myForm").validation();
});

// We can check if the form is valid on demand, using our validate function
function preValidateLeadForm(inp) {
	var $form = $(inp).closest("form");

	// Lead Type and Lead Source are required
	var isValid = false,
		leadTypeId = parseInt($form.find("#toolbargroup .sel-lead-type input[name='LeadTypeId']").val()),
		leadSourceId = parseInt($form.find("#toolbargroup .sel-lead-source select:first").val());

	if (!isNaN(leadSourceId) && leadSourceId > 0) {

		if (!$form.find("#toolbargroup .sel-lead-type select:first option").length
			|| (!isNaN(leadTypeId) && leadTypeId > 0)) {

			isValid = true;
		}
	}

	if (isValid) {
		var groupErrorMessage = $form.find('#errorMessages');

		if ($form.validate()) {
			groupErrorMessage.hide();
			$(".fancybox-skin, #fancybox-overlay").show();

			$.fancybox($("#popup-sumitting"), {
				padding: 0,
				closeBtn: false,
				helpers: {
					overlay: {
						opacity: 0.6,
						css: {
							'background-color': '#11619D'
						}
					}
				},
				beforeClose: function () {
					return false;
				}
			});

			return true;
		}
		else {
			// Add Error
			groupErrorMessage.find(".errorgrid")
				.html('<strong>Error: Invalid Data</strong><span>The form has not been saved; please correct the following errors:<br /></span><ul class="errorlist" style="margin-top:10px; margin-left:20px"></ul>');

			// Find error message
			$form.find("#grouptab a.nexttab").each(function() {
				var $lnk = $(this),
					tabName = $lnk.text();

				$("ul" + $lnk.attr("href").replace(/^.*?#+/g, "#") + " li").each(function() {
					$(this).find(".error-desc").each(function() {
						groupErrorMessage.find(".errorlist").append("<li>" + tabName + " &raquo; " + $(this).html() + "</li>");
					});
				});
			});

			groupErrorMessage.show();
		}
	}

	return false;
}

// Show tooltip delete appointment
$(function() {
	$('.btn-x').set_action_tooltip({
		width: 150,
		offset_x: 14,
		offset_y: -7,
		cancel_class: 'btn btn-cancel-small left',
		continue_class: 'btn btn-delete-small right'
	});
});
// END


var editLeadViewModel = new function () {
	this.LeadId = ko.observable(data.LeadId);

	//this.OriginalLeadType = ko.observable(data.LeadTypeId);
	this.LeadType = ko.observable(data.LeadSelected); // Use LeadSelected instead of LeadTypeId
	this.LeadTypeOptions = ko.observableArray(data.LeadType);

	this.LeadSource = ko.observable(data.LeadSourceId);
	this.LeadSourceOptions = ko.observableArray(data.LeadSource);

	this.User = ko.observable(data.UserId);
	this.Owner = ko.observable(data.UserId);
	this.UserOptions = ko.observableArray(data.UserFilter);

	// Add new requirement
	this.EnableLeadType = ko.computed(function () {
		return !(!this.LeadTypeOptions() || !this.LeadTypeOptions().length || this.LeadTypeOptions().length <= 1);
	}, this);
	this.PleaseMessage = ko.computed(function () {
		return (!this.EnableLeadType()) ? "Please select Lead Source to enable the form below."
			: "Please select Lead Type and Lead Source to enable the form below.";
	}, this);

	// Added Action
	this.Action = ko.observable(data.ListAction.Selected != null ? data.ListAction.Selected : 0);
	this.ActionOptions = ko.observableArray(data.ListAction.ListActionType);
	console.log(data.ListAction.ListAccountLog.length);

	this.ListAccountLog = ko.observableArray(data.ListAction.ListAccountLog);
	this.Comment = ko.observable("");
	this.Required = ko.observable(false);
	this.CommitAction = function () {
		// Build a function to post data
		var actionId = parseInt(this.Action());
		var isValid = true;
		var comment = this.Comment();

		for (var i = 0; i < this.ActionOptions().length; i++) {
			if (parseInt(this.ActionOptions()[i].ID) == actionId && this.ActionOptions()[i].IsRequired && comment == "") {
				isValid = false;
				break;
			}
		}

		if (!isValid) {
			this.Required(!isValid);

			$('#commentError').attr("style", "");
			$('#commentError').text("Comment is required");
			$('#actionComment').addClass("error");

			return false;
		}
		else {
			if (comment.length > 1000) {
				$('#commentError').attr("style", "");
				$('#commentError').text("Please enter less than 1001 characters");
				$('#actionComment').addClass("error");
			}
			else {
				var dataPost = { "id": this.LeadId(), "actionid": actionId, "comment": comment };

				// Ajax request
				$.ajax({
					type: "POST",
					url: "/Lead/AddAction",
					data: dataPost,
					dataType: "json",
					success: function (model, textStatus, jqXHR) {
						if (model && typeof model.Status != "undefined" && (typeof model.Error == "undefined" || !model.Error)) {

							$('#status').text(model.Status);
							editLeadViewModel.ListAccountLog(model.ListAccountLog);
							editLeadViewModel.ActionOptions(model.ListActionType);

							// Refresh dropdown data
							editLeadViewModel.Action(model.ListActionType == null || model.ListActionType != undefined ? 0 : model.ListActionType[0].ID);

							// Refresh dropdown
							var tempEl = document.getElementById("actionType");
							if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
							jcf.customForms.replaceElement("actionType");
							// Must be executed after knockout rendering
							setTimeout("jcf.customForms.replaceElement('actionType')", 0);

							resizeAction();
						}
						else {
							showPopupError();
						}
					},
					error: function (xhr, status, error) {
						showPopupError();
					}
				});

				$('#actionComment').removeClass("error").removeClass("text-active");
				$('#commentError').hide();
				this.Comment("");
				this.Required(false);
			}
		}
	};

	// Added Appointment
	this.Duration = ko.observable(data.ListAppointment.ListDuration[0].ID);
	this.DurationOptions = ko.observableArray(data.ListAppointment.ListDuration);
	this.LeadScheduleAppointment = ko.observableArray(data.ListAppointment.ListAppointments);
	this.Subject = ko.observable("").extend({ required: { message: "Subject is required"} });
	var now = new Date();
	var dateNow = (now.getMonth() + 1) + "/" + now.getDate() + "/" + now.getFullYear();
	this.Date = ko.observable(dateNow).extend({ required: { message: "Date is required"} }).extend({
		pattern: {
			message: 'Enter a valid Date',
			params: '^(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/(19\\d\\d|(20)?[0-7][0-8])$'
		}
	});

	this.Time = ko.observable("").extend({ required: { message: "Time is required"} }).extend({
		pattern: {
			message: 'Enter a valid Start Time',
			params: '^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])? ([pa]m|[PA]M)$'
		}
	});
	this.Reminder = ko.observable("0 minutes");
	this.GroupUpdateShow = ko.observable(false);
	this.SetShow = ko.observable(true);
	this.AppointmentId = ko.observable(0);

	this.editLine = function (line) {
		$('#subject').val(line.Title);
		$('#date').val(line.StartDate);
		$('#time').val(line.StartTime);

		// Set duration / reminder
		$("#duration option[value='" + line.Duration + "']").attr("selected", "selected");
		$("#groupTime .center").text($("#duration option[value='" + line.Duration + "']").text());
		$('input:radio[name=reminder]').filter('[value="' + line.Reminder + '"]').attr('checked', true);

		// Knockout property
		editLeadViewModel.Subject(line.Title);
		editLeadViewModel.Date(line.StartDate);
		editLeadViewModel.Time(line.StartTime);
		editLeadViewModel.Duration(line.Duration);
		editLeadViewModel.Reminder(line.Reminder);
		editLeadViewModel.GroupUpdateShow(true);
		editLeadViewModel.SetShow(false);
		editLeadViewModel.AppointmentId(line.Id);

		// Set grayed line selected for edit
		$("ul#app-list li").each(function () {
			$(this).removeClass("line-selected");
		});
		$('#appointment' + line.Id).parents("li").addClass("line-selected");
	};

	this.DeleteAppointment = function () {
		var appId = $('#appointmentId').val();
		var dataPost = { "id": appId };
		var line;
		for (var i = 0; i < editLeadViewModel.LeadScheduleAppointment().length; i++) {
			if (editLeadViewModel.LeadScheduleAppointment()[i].Id == appId) {
				line = editLeadViewModel.LeadScheduleAppointment()[i];
				break;
			}
		}

		// Ajax request
		$.ajax({
			type: "POST",
			url: "/Lead/DeleteAppointment",
			data: dataPost,
			dataType: "json",
			success: function (model, textStatus, jqXHR) {
				if (typeof model != "undefined" && (model === "" || typeof model.Error == "undefined" || !model.Error)) {

					editLeadViewModel.LeadScheduleAppointment.remove(line);
					editLeadViewModel.AppointmentId(0);
					$("#subject").val('');
					$("#date").val('');
					$("#time").val('');

					// auto calculate height of all items
					resizeAppointment();

					// Close
					// Refresh
					$('.btn-x').set_action_tooltip({
						width: 150,
						offset_x: 14,
						offset_y: -7,
						cancel_class: 'btn btn-cancel-small left',
						continue_class: 'btn btn-delete-small right'
					});
				}
				else {
					showPopupError();
				}
			},
			error: function (xhr, status, error) {
				showPopupError();
			}
		});
		editLeadViewModel.GroupUpdateShow(false);
		editLeadViewModel.SetShow(true);
	};

	this.UpdateAppointment = function () {
		if ($("#subject").val() == '') {
			this.Subject('');
		}
		if ($("#date").val() == '') {
			this.Date('');
		}
		if ($("#time").val() == '') {
			this.Time('');
		}

		if (editLeadViewModel.errors().length == 0) {
			// Build a function to post data
			if (this.AppointmentId() > 0) {
				var dataPost = {
					"id": this.AppointmentId(),
					"leadid": this.LeadId(),
					"userid": this.User(),
					"subject": this.Subject(),
					"startdate": this.Date() + " " + this.Time(),
					"duration": this.Duration(),
					"reminder": this.Reminder()
				};

				// Ajax request
				$.ajax({
					type: "POST",
					url: "/Lead/EditAppointment",
					data: dataPost,
					dataType: "json",
					success: function (model, textStatus, jqXHR) {
						if (model && typeof model.ListAppointments != "undefined" && (typeof model.Error == "undefined" || !model.Error)) {

							editLeadViewModel.LeadScheduleAppointment(model.ListAppointments);
							// Set to default value
							editLeadViewModel.AppointmentId(0);
							editLeadViewModel.GroupUpdateShow(false);
							editLeadViewModel.SetShow(true);

							// auto calculate height of all items
							resizeAppointment();

							//Refresh
							$('.btn-x').set_action_tooltip({
								width: 150,
								offset_x: 14,
								offset_y: -7,
								cancel_class: 'btn btn-cancel-small left',
								continue_class: 'btn btn-delete-small right'
							});
						}
						else {
							showPopupError();
						}
					},
					error: function (xhr, status, error) {
						showPopupError();
					}
				});
				// End Ajax
			}

			$("#subject").val('');
			$("#date").val('');
			$("#time").val('');
			$("#appointment .row").each(function () {
				$(this).find("input.text").removeClass("text-active");
			});
		}
		else {
			editLeadViewModel.errors.showAllMessages();
		}
	};

	this.CancelAppointment = function () {
		$("#subject").val("");
		$("#date").val("");
		$("#time").val("");
		editLeadViewModel.Duration(30);
		editLeadViewModel.Reminder("0 minutes");
		editLeadViewModel.AppointmentId(0);
		editLeadViewModel.GroupUpdateShow(false);
		editLeadViewModel.SetShow(true);
		$("ul#app-list li").each(function () {
			$(this).removeClass("line-selected");
		});
	};

	this.SetAppointment = function () {
		if ($("#subject").val() == '') {
			this.Subject('');
		}
		if ($("#date").val() == '') {
			this.Date('');
		}
		if ($("#time").val() == '') {
			this.Time('');
		}

		if (editLeadViewModel.errors().length == 0) {

			// Build a function to post data
			if (this.AppointmentId() <= 0) {
				var dataPost = {
					"leadid": this.LeadId(),
					"userid": this.Owner(),
					"subject": this.Subject(),
					"startdate": this.Date() + " " + this.Time(),
					"duration": this.Duration(),
					"reminder": this.Reminder()
				};

				// Ajax request
				$.ajax({
					type: "POST",
					url: "/Lead/AddAppointment",
					data: dataPost,
					dataType: "json",
					success: function (model, textStatus, jqXHR) {
						if (model && typeof model.ListAppointments != "undefined" && (typeof model.Error == "undefined" || !model.Error)) {

							editLeadViewModel.LeadScheduleAppointment(model.ListAppointments);
							// Set to default value
							editLeadViewModel.AppointmentId(0);
							editLeadViewModel.GroupUpdateShow(false);
							editLeadViewModel.SetShow(true);

							// auto calculate height of all items
							resizeAppointment();

							// Refresh
							$('.btn-x').set_action_tooltip({
								width: 150,
								offset_x: 14,
								offset_y: -7,
								cancel_class: 'btn btn-cancel-small left',
								continue_class: 'btn btn-delete-small right'
							});
						}
						else {
							showPopupError();
						}
					},
					error: function (xhr, status, error) {
						showPopupError();
					}
				});
				// End Ajax
			}

			$("#subject").val('');
			$("#date").val('');
			$("#time").val('');
			$("#appointment .row").each(function () {
				$(this).find("input.text").removeClass("text-active");
			});
		}
		else {
			editLeadViewModel.errors.showAllMessages();
		}
	};
};

// Apply view model
editLeadViewModel.errors = ko.validation.group(editLeadViewModel);
ko.applyBindings(editLeadViewModel, document.getElementById("main"));

function UpdateEmail(emailId) {
	$(":text").each(function() {
		var id = $(this).attr("id");
		if (id == emailId) {
			$(this).removeAttr("readonly");
			$(this).removeClass("readonly");
			$(this).css("display", "inline-block");
			$("#strong" + id).css("display", "none");
			$("#link" + id).css("display", "none");
			$("#span" + id).css("display", "inline-block");

			// Set required
			if ($("#hid" + id).val() == "require") {
				$(this).attr("validation", "required email");
			}

			// Refresh
			$("#myForm").validation();
		}
	});
}

function dialIDCallPhone(leadId, phone) {
	var dataPost = { "leadId": leadId, "leadPhone": phone };

	// Ajax call function
	// Ajax request
	$.ajax({
		type: "POST",
		url: "/Lead/PlaceACall",
		data: dataPost,
		dataType: "json",
		success: function(model, textStatus, jqXHR) {
			if (typeof model != "undefined" && (model === "" || typeof model.Error == "undefined" || !model.Error)) {
			}
			else {
				showDialError();
			}
		},
		error: function(xhr, status, error) {
			showDialError();
		}
	});
}

function OpenPrintLeadWindow() {
	var url = "/Lead/PrintLead/" + data.LeadId,
		widthPopup = 968,
		heightPopup = 500,
		leftPopup = (screen.width / 2) - (widthPopup / 2),
		topPopup = (screen.height / 2) - (heightPopup / 2);

	window.open(url, '', 'left=' + leftPopup + ',top=' + topPopup + ',width=' + widthPopup + ',height=' + heightPopup + ',scrollbars=yes,toolbar=0,status=0');
}
